﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using SqlSugar;
using Surging.Core.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{
    /// <summary>
    /// 美程用户表仓储层
    /// </summary>
    public class DoraUserRepository : SqlSugarRepository<DoraUserEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public DoraUserRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<DoraUserListDto>> GetPageList(DoraUserQueryDto input)
        {
            var pagePredict = _unitOfWork.QueryClient.Queryable<DoraUserEntity>()
                .Where(it => it.IsDeleted == 0)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Keywords), it => it.Mobile.Contains(input.Keywords.Trim()) ||  it.UserName.Contains(input.Keywords.Trim())
                || it.RealName.Contains(input.Keywords.Trim()) || it.Email.Contains(input.Keywords.Trim()));
            var totalCount = await pagePredict.CountAsync();
            var pageList = await pagePredict.OrderBy(it => it.CreatedTime, OrderByType.Desc)
                .Select((it) => new DoraUserListDto
                {
                    Id = it.Id,
                    UserName = it.UserName,
                    Mobile = it.Mobile,
                    MobileIsVerified = it.MobileIsVerified,
                    Email = it.Email,
                    EmailIsVerified = it.EmailIsVerified,
                    RealName = it.RealName,
                    Sex = it.Sex,
                    Sort = it.Sort,
                    IsDisabled = it.IsDisabled,
                    IsFrozen = it.IsFrozen,
                    IsSuperAdmin = it.IsSuperAdmin,
                    Avatar = it.Avatar,
                    Remark = it.Remark
                })
                .ToPageListAsync(input.PageIndex, input.PageSize);
            
            var page = new PageDataList<DoraUserListDto>(totalCount, pageList, input.PageIndex, input.PageSize);
            return page;
        }

        /// <summary>
        /// 根据用户名获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<DoraUserEntity> GetByUserName(string userName)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().FirstAsync(item => item.UserName == userName);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Delete(Guid id) 
        {
            var result = await _unitOfWork.ModifyClient.Updateable<DoraUserEntity>()
                .SetColumns(it => new DoraUserEntity() { IsDeleted = 1, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == id).ExecuteCommandAsync()>0;
            return result;
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<DoraUserEntity> GetByMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().FirstAsync(it => it.Mobile == mobile && it.IsDeleted == 0);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<DoraUserEntity> GetByVerifiedMobile(string mobile)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().FirstAsync(it => it.Mobile == mobile && it.MobileIsVerified == 1 && it.IsDeleted == 0);
        }

        /// <summary>
        /// 根据手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<DoraUserEntity> GetByEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().FirstAsync(it => it.Email == email && it.IsDeleted == 0);
        }

        /// <summary>
        /// 根据验证后的手机号获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<DoraUserEntity> GetByVerifiedEmail(string email)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().FirstAsync(it => it.Email == email && it.EmailIsVerified == 1 && it.IsDeleted == 0);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePassword(DoraUserEntity entity)
        {
            //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new { it.Password, it.UpdatedTime }).ExecuteCommandAsync() > 0;
            var result = await _unitOfWork.ModifyClient.Updateable<DoraUserEntity>()
                .SetColumns(it => new DoraUserEntity() { Password = entity.Password, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        //public async Task<bool> UpdateLastLoginTime(DoraUserEntity entity)
        //{
        //    //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new { it.Password, it.UpdatedTime }).ExecuteCommandAsync() > 0;

        //    var result = await _unitOfWork.ModifyClient.Updateable<DoraUserEntity>()
        //        .UpdateColumns(it => new DoraUserEntity() { LastLoginTime = entity.ThisLoginTime, ThisLoginTime = DateTime.Now })
        //        .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
        //    return result;
        //}

        /// <summary>
        /// 禁用/启用用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsDisabled(DoraUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<DoraUserEntity>()
                .SetColumns(it => new DoraUserEntity() { IsDisabled = entity.IsDisabled, UpdatedTime = entity.UpdatedTime,UpdatedUserId=entity.UpdatedUserId,UpdatedUserName=entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 冻结/解冻用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> IsFrozen(DoraUserEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<DoraUserEntity>()
                .SetColumns(it => new DoraUserEntity() { IsFrozen = entity.IsFrozen, UpdatedTime = entity.UpdatedTime, UpdatedUserId = entity.UpdatedUserId, UpdatedUserName = entity.UpdatedUserName })
                .Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
            return result;
        }
        ///// <summary>
        ///// 修改
        ///// </summary>
        ///// <param name="entity"></param>
        ///// <returns></returns>
        //public new async Task<bool> Update(DoraUserEntity entity)
        //{
        //    var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new {
        //        //it.Id,
        //        //it.UserName,
        //        //it.Password,
        //        //it.PasswordSalt,
        //        it.Mobile,
        //        //it.MobileIsVerified,
        //        it.Email,
        //        //it.EmailIsVerified,
        //        it.RealName,
        //        it.Sex,
        //        it.IDCardNO,
        //        it.Sort,
        //        //it.IsDisabled,
        //        //it.IsFrozen,
        //        //it.IsSuperAdmin,
        //        it.Avatar,
        //        it.Remark,
        //        //it.IsDeleted,
        //        //it.CreatedUserId,
        //        //it.CreatedUserName,
        //        //it.CreatedTime,
        //        it.UpdatedUserId,
        //        it.UpdatedUserName,
        //        it.UpdatedTime,
        //    }).ExecuteCommandAsync() > 0;
        //    return result;
        //}

        /// <summary>
        /// 验证后的手机号是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistVerifiedMobile(string mobile,Guid id)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().Where(it => it.Mobile == mobile && it.MobileIsVerified == 1 && it.IsDeleted == 0 && it.Id!=id).CountAsync()>0;
        }

        /// <summary>
        /// 验证用户名是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistUserName(string userName, Guid id)
        {
            return await _unitOfWork.QueryClient.Queryable<DoraUserEntity>().Where(it => it.UserName == userName && it.IsDeleted == 0 && it.Id != id).CountAsync() > 0;
        }
    }
}
